/*
 * campfire, formerly known as bandcampDirect
 * Copyright (C) 2020 Fynn Godau
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Not affiliated with bandcamp, Incorporated.
 */

package godau.fynn.bandcampdirect.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import godau.fynn.bandcampdirect.BuildConfig;
import godau.fynn.bandcampdirect.R;
import godau.fynn.bandcampdirect.SharedPreferences;
import godau.fynn.bandcampdirect.adapter.FavoritesAdapter;
import godau.fynn.bandcampdirect.discover.Database;
import godau.fynn.bandcampdirect.model.Album;
import godau.fynn.bandcampdirect.model.Track;
import godau.fynn.librariesdirect.AboutDirectActivity;
import godau.fynn.librariesdirect.model.Library;
import godau.fynn.librariesdirect.model.License;
import godau.fynn.librariesdirect.model.OwnLicense;
import godau.fynn.librariesdirect.model.Imprint;

import java.util.List;

public class FavoritesActivity extends Activity {

    private static final int REQUEST_DISCOVER = 1;
    private static final int REQUEST_SEARCH = 2;
    private static final int REQUEST_LOGIN = 3;

    private Database database;
    private FavoritesAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorites);

        setTitle("discover database | campfire");

        SharedPreferences sharedPreferences = new SharedPreferences(FavoritesActivity.this);
        database = Database.build(FavoritesActivity.this);


        RecyclerView trackLayout = findViewById(R.id.tracks);
        trackLayout.setLayoutManager(new LinearLayoutManager(FavoritesActivity.this));

        new Thread(() -> {

            List<Track> trackList = database.trackDao().getAll();
            List<Album> albums = database.albumDao().getAll();

            // Assign each album to a track
            categorizing:
            for (Track t :
                    trackList) {
                // Find a matching album

                searching:
                for (Album a :
                        albums) {
                    if (a.getId() == t.getAlbumId()) {
                        // match
                        a.getTracks().add(t);
                        continue categorizing;
                    } else {
                        continue searching;
                    }
                }
            }

            // Order every album
            for (Album a :
                    albums) {
                a.orderTracks();
            }

            // Tracks have been loaded, display them in UI
            runOnUiThread(() -> {
                trackLayout.setAdapter(adapter = new FavoritesAdapter(albums, database));

                if (albums.size() == 0) {
                    findViewById(R.id.empty).setVisibility(View.VISIBLE);
                }
            }
            );

        }).start();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about: {
                Intent intent = new AboutDirectActivity.IntentBuilder(FavoritesActivity.this, R.string.app_name, BuildConfig.VERSION_NAME)
                        .setAppDeveloperName("Fynn Godau")
                        .setIcon(R.mipmap.ic_launcher)
                        .setContent(new Object[]{
                                new OwnLicense(License.GNU_GPL_V3_OR_LATER_LICENSE),
                                new Library("NewPipeExtractor", License.GNU_GPL_V3_OR_LATER_LICENSE, null, "TeamNewPipe", true, "https://newpipe.net"),
                                new Library("OkHttp", License.APACHE_20_LICENSE, null, "Square, Inc.", false, "https://square.github.io/okhttp/"),
                                new Library("Volley", License.APACHE_20_LICENSE, null, "Google, Inc.", false, "https://developer.android.com/training/volley/index.html"),
                                new Library("jsoup", License.MIT_LICENSE, "Copyright © 2009 - 2019 Jonathan Hedley (jonathan@hedley.net)", "Jonathan Hedley", false, "https://jsoup.org"),
                                new Library("TypedRecyclerView", License.CC0_LICENSE, null, "Fynn Godau", false, "https://codeberg.org/fynngodau/TypedRecyclerView"),
                                new Library("librariesDirect", License.CC0_LICENSE, null, "Fynn Godau", false, "https://codeberg.org/fynngodau/librariesDirect"),
                                new Imprint("Fynn Godau\n" +
                                        "Stößelstraße 6\n" +
                                        "97422 Schweinfurt\n" +
                                        "Deutschland\n" +
                                        "\n" +
                                        "fynngodau@mailbox.org\n" +
                                        "+49 9721 730335\n" +
                                        "\n" +
                                        "Umsatzsteuer-Identifikationsnummer (VAT identification number): DE347187327\n" +
                                        "\n" +
                                        "Plattform der EU zur außergerichtlichen Streitbeilegung\n" +
                                        "(EU platform for Online Dispute Resolution):\n" +
                                        "https://ec.europa.eu/consumers/odr/")
                        }).build();
                startActivity(intent);
                break;
            }
            case R.id.action_search:

                View view = View.inflate(FavoritesActivity.this, R.layout.popup_edittext, null);
                EditText editText = view.findViewById(R.id.edit);

                new AlertDialog.Builder(FavoritesActivity.this)
                        .setTitle("Search")
                        .setView(view)
                        .setPositiveButton("OK", (dialog, which) -> {
                            Intent intent = new Intent(FavoritesActivity.this, SearchActivity.class);
                            intent.putExtra(SearchActivity.EXTRA_QUERY, editText.getText().toString());
                            startActivityForResult(intent, REQUEST_SEARCH);
                        })
                        .setNegativeButton("Cancel", null)
                        .show();
                break;
            case R.id.action_login:
                startActivityForResult(
                        new Intent(FavoritesActivity.this, LoginActivity.class), REQUEST_LOGIN);
                break;
            case R.id.action_flush_discover_database:
                new AlertDialog.Builder(FavoritesActivity.this)
                        .setTitle(R.string.flush_dialog_title)
                        .setMessage(R.string.flush_dialog_message)
                        .setPositiveButton(R.string.yes, (dialog, which) -> new Thread(() -> {
                            database.flush();
                            runOnUiThread(() -> {
                                adapter.clear();
                                findViewById(R.id.empty).setVisibility(View.VISIBLE);
                            });
                        }).start())
                        .setNegativeButton(R.string.no, null)
                        .show();
                break;
            case R.id.action_discover:
                startActivityForResult(new Intent(
                                FavoritesActivity.this, DiscoverActivity.class),
                        REQUEST_DISCOVER);
                break;
            /*case R.id.action_cart:
                startActivity(new Intent(FavoritesActivity.this, CartActivity.class));
                break;*/

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (resultCode == RESULT_OK) {
            recreate();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}
